<template>
  <div>
    <div class="control-Action-page">
      <!-- aside -->
      <div class="manage-page-aside">
        <div class="head-section" style="overflow: hidden">

          <h3 class="table-head">网点列表：</h3>
          <el-select @change="organChangeEvent" v-model="organId" placeholder="请选择" value-key="item" style="width:1.5rem">
            <el-option v-for="item in organOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>

          <el-switch :active-value="1" :inactive-value="0" @change="changeJobByOrgan()" active-color="#13ce66"
            inactive-color="#ff4949" v-model="changeJobByOrganId" active-text="启用" inactive-text="停用"></el-switch>
            <el-tooltip class="item" effect="dark" content="单设备策略功能停用" placement="right">
      <i class="el-icon-warning-outline" style="color: #fff;font-size: 20px;margin-left: 10px;"></i>
    </el-tooltip>
        </div>
        <div class="table-section" style="border: 1px solid #fff;">
          <el-scrollbar wrap-class="scrollbar-wrapper" style="height: 100%">
            <el-tree ref="refAreaTree" :data="areaData" :render-content="renderContent" :props="defaultProps"
              default-expand-all node-key="id" @node-click="handleNodeClick" highlight-current
              :expand-on-click-node="false"></el-tree>
          </el-scrollbar>
        </div>
      </div>
      <!-- content -->
      <div class="content manage-page-content">
        <div class="userList-section">
          <div class="head-section">
            <div class="head-section">
              <h3 class="table-head">包含的电器</h3>
            </div>

          </div>
          <div>
            <el-table :data="tableData" border height="410" ref="multipleTable" highlight-current-row
              @row-click="handleCurrentChange">
              <el-table-column type="index" label="序号" width="60">
              </el-table-column>
              <el-table-column prop="channelName" label="通道名称">
              </el-table-column>
              <!-- <el-table-column prop="guid" label="GUID" width="100"> </el-table-column> -->
              <el-table-column prop="probeMoldCode" label="通道类型" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.probeKindName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="channel" label="通道序号" width="80">
              </el-table-column>

              <el-table-column prop="probeGuid" label="GUID" width="150">
              </el-table-column>

              <el-table-column prop="state" label="状态" width="60">
                <template slot-scope="scope">
                  <span>{{ scope.row.state == "0" ? "关闭" : "开启" }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="lastOnOffTime" label="最后通讯时间" width="160">
              </el-table-column>
            </el-table>

          </div>
        </div>
        <div class="areaList-section" style="margin-top:10px">
          <div class="head-section">
            <div class="head-section">
              <header>
                <el-button @click="handleAddProbeChannelTask()" size="medium" type="primary" plain>新增定时任务
                </el-button>
              </header>
              <h3 class="table-head">设备定时</h3>
            </div>

          </div>
          <div>
            <el-table :data="probeTasktableData" border :stripe="true" height="410"
              @selection-change="handleSelectionChange">
              <el-table-column type="index" label="序号" width="60">
              </el-table-column>

              <el-table-column prop="runTime" label="时间" width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.runTime" type="time" @focus="timeChange(scope.row)"
                    @blur="operationChange(scope.row, $event)" style="width: auto"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="weekdayStr" label="重复" style="cursor: pointer" width="350">
                <template slot-scope="scope">
                  <el-checkbox-group :min="1" v-model="scope.row.runWeekstr" @change="
                    (val) => {
                      checkboxOptions(val, scope.row);
                    }
                  ">
                    <el-checkbox v-for="item in weekOptions" :key="item.id" :label="item.id">
                      {{ item.name }}
                    </el-checkbox>
                  </el-checkbox-group>
                </template>
              </el-table-column>

              <el-table-column prop="runState" label="控制" style="cursor: pointer">
                <template slot-scope="scope">
                  <el-radio-group v-model="scope.row.runState" @change="operationChange(scope.row)">
                    <el-radio label="1">开</el-radio>
                    <el-radio label="0">关</el-radio>
                  </el-radio-group>

                </template>
              </el-table-column>
              <el-table-column prop="runState" label="启用" style="cursor: pointer">
                <template slot-scope="scope">
                  <el-switch @change="operationChange(scope.row)" :active-value="1" :inactive-value="0"
                    active-color="#13ce66" inactive-color="#ff4949" v-model="scope.row.enable" active-text="启用"
                    inactive-text="停用"></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                  <el-button type="primary" size="small" @click="handleDeleteOperation(scope.row)">删除</el-button>
                </template>

              </el-table-column>
            </el-table>

          </div>
        </div>
      </div>
    </div>

    <div>
      <el-dialog class="same-dia" title="新增操作" :visible.sync="dialogOperationVisible" width="500px"
        @close="resetOperaForm" :close-on-click-modal="false">
        <el-form :rules="rules" :model="pojoOperation" ref="pojoOperaForm" label-width="100px">
          <el-form-item label="重复：" prop="runWeek">
            <el-checkbox-group v-model="pojoOperation.runWeek">
              <el-checkbox v-for="item in weekOptions" :key="item.id" :label="item.id">{{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="时间：" prop="time">
            <el-time-picker v-model="pojoOperation.runTime" format="HH:mm" placeholder="选择时间">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="操作：" prop="remark">
            <el-radio v-model="pojoOperation.runState" :label="1">开</el-radio>
            <el-radio v-model="pojoOperation.runState" :label="0">关</el-radio>
          </el-form-item>
          <el-form-item label="是否启用：" prop="enable">
            <el-switch :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949"
              v-model="pojoOperation.enable" active-text="启用" inactive-text="停用"></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addOperationSubmit('pojoOperaForm')">确 定
          </el-button>
          <el-button @click="dialogOperationVisible = false">取 消</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import ajax from "@/utils/ajax";
import date from "@/utils/date";
import { tableSelection, deleteConfirm } from "@/utils/elementui.js";
export default {
  data() {
    return {
      organId: '',
      organOptions: [],
      permission: {
        add: false,
        modify: false,
        delete: false,
        bind_strategy: false,
        add_area_channel: false,
        delete_area_channel: false,
      },
      customerId: "",

      currentAction: null,
      options: [],
      ActionAppliancesData: [],
      tableIndex: 0,
      //区域
      areaData: [],
      areaid: "",
      defaultProps: {
        children: "children",
        label: "name",
      },
      tableData: [],
      multipleSelection: [],
      channelId: null,
      probeId: null,
      probeGuid: null,
      channelName: null,
      probeTasktableData: [],
      weekOptions: [
        { id: 1, name: "周日" },
        { id: 2, name: "周一" },
        { id: 3, name: "周二" },
        { id: 4, name: "周三" },
        { id: 5, name: "周四" },
        { id: 6, name: "周五" },
        { id: 7, name: "周六" },
      ],
      pojoOperation: {

        runWeek: [],
        runTime: "",
        runState: 0,
        enable: 1,
        channelId: null,
        probeId: null,
        probeGuid: null,
        channelName: null,
      },
      rules: {

        runWeek: [
          { required: true, message: "请选择重复的类型", trigger: "blur" },
        ],

        runTime: [{ required: true, message: "时间不能为空", trigger: "blur" }],
      },
      dialogOperationVisible: false,
      changeJobByOrganId: null,
      OrganIdindex:0
    };
  },
  created() {
    this.customerId = this.$store.getters.customerId;

  },
  mounted() {
    this.$store.dispatch("actions/dynamicTitleAction", this.$route.meta.title);
    this.getOrganListData();

  },

  methods: {

    // 设置可操作的权限
    setPermission() {
      let role_permissions = this.$store.getters.rolePermissions;
      console.log("-----------------------", role_permissions);
      for (let item of role_permissions) {
        if (item.action === "/web/control_Action") {
          for (let permission of item.privilegeList) {
            switch (permission.action) {
              case "/web/control_Action/add":
                this.permission.add = true;
                break;
              case "/web/control_Action/modify":
                this.permission.modify = true;
                break;
              case "/web/control_Action/delete":
                this.permission.delete = true;
                break;
              case "/web/control_Action/bind_strategy":
                this.permission.bind_strategy = true;
                break;
              case "/web/control_Action/add_area_channel":
                this.permission.add_area_channel = true;
                break;
              case "/web/control_Action/delete_area_channel":
                this.permission.delete_area_channel = true;
                break;
              default:
                break;
            }
          }
        }
      }
    },
    // 获取网点列表
    getOrganListData() {
      ajax.get({
        url: this.$API.getUserOrgan + this.$store.getters.user.id,
        success: (response) => {
          const resp = response.data;
          if (resp.length > 0) {
            this.organOptions = resp;
            this.organId = resp[0].id
            this.changeJobByOrganId = resp[0].probeChannelTask !=null?resp[0].probeChannelTask:1
            this.getAreaTreeByOrganId()
          } else {
            this.organOptions = [];
          }
        },
        error: (res) => {
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },

    organChangeEvent() {
      let probeChannelTask = this.organOptions.filter(data => data.id == this.organId)[0].probeChannelTask
      this.OrganIdindex =this.organOptions.findIndex(data => data.id == this.organId)
      this.changeJobByOrganId = probeChannelTask !=null?probeChannelTask:1
      this.getAreaTreeByOrganId()
    },
    //通过网点获取区域列表
    getAreaTreeByOrganId() {
      ajax.get({
        url: this.$API.getAreaTreeByOrganId + this.organId,
        success: (response) => {

          this.areaData = response.data;
          this.options = response.data;
          const resp = response.data;
          if (resp.length > 0) {
            this.areaId = resp[0].id;
            this.getProbechannelListData();
            this.$nextTick(() => {
              this.$refs.refAreaTree.setCurrentKey(resp[0].id);
            });
          } else {
            this.areaData = [];
            this.areaId = null;
          }
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 根据区域id获取探头数据
    getProbechannelListData() {

      ajax.get({
        url: this.$API.getProbeChannelInfoByAreaId + this.areaId,

        success: (response) => {

          if (response.data.length > 0) {
            this.tableData = response.data;

            this.$nextTick(() => {
              let index = this.tableIndex;

              this.$refs.multipleTable.setCurrentRow(
                this.$refs.multipleTable.data[index]
              );

              this.channelId = response.data[index].id;
              this.probeId = response.data[index].probeId
              this.probeGuid = response.data[index].probeGuid
              this.channelName = response.data[index].channelName
              this.getProbeChannelTask();
            });
          } else {
            this.tableData = [];
          }

        },
        error: (response) => {
          this.$message({
            message: response.message,
            type: "error",
          });
        },
      });
    },
    // 多选
    handleSelectionChange(val) {
      //console.log(val)
      this.multipleSelection = val;
      console.log(val)

    },
    handleCurrentChange(row) {
      // this.currentGroup = row;
      this.channelId = row.id;
      this.probeId = row.probeId
      this.probeGuid = row.probeGuid
      this.channelName = row.channelName
      this.tableIndex = row.index;

      this.$nextTick(() => {
        this.getProbeChannelTask();
      });
    },
    getProbeChannelTask() {
      ajax.get({
        url: this.$API.getProbeChannelTask + this.channelId,

        success: (response) => {
          for (let item of response.data) {
            item.runWeekstr =
              item.runWeek != ""
                ? item.runWeek.split(",").map(parseFloat)
                : [];
          }
          this.probeTasktableData = response.data;
        },
        error: (response) => {
          this.$message({
            message: response.message,
            type: "error",
          });
        },
      });
    },
    // 添加控制策略包含的操作
    handleAddProbeChannelTask() {
      this.dialogOperationVisible = true;
    },

    // 提交控制策略
    addOperationSubmit(fromName) {
      this.$refs[fromName].validate((valid) => {
        if (valid) {
          let pojodata = this.pojoOperation;
          pojodata.runWeek = pojodata.runWeek.join(",");
          pojodata.runTime = date.formatHourTime(new Date(this.pojoOperation.runTime))
          pojodata.channelId = this.channelId
          pojodata.probeId = this.probeId
          pojodata.probeGuid = this.probeGuid
          pojodata.channelName = this.channelName
          ajax.post({
            url: this.$API.createProbeChannelTask,
            data: pojodata,
            success: (response) => {
              if (response.success) {
                this.getProbeChannelTask();
                this.dialogOperationVisible = false;
                this.$message({
                  message: response.message,
                  type: "success",
                });
              }
            },
            error: (response) => {
              this.$message({
                message: response.message,
                type: "error",
              });
            },
          });
        }
      });
    },
    resetOperaForm() {
      this.$refs["pojoOperaForm"].resetFields();
      this.pojoOperation.runTime = new Date()
    },
    // 点击区域
    handleNodeClick(data) {
      this.areaId = data.id;
      let attr = []
      for (let i of getParentIdList(this.areaData, data.id)) {
        attr.push(i.id)
      }
      this.areaIds = attr.join(',')
      this.currentPage = 1;
      this.getProbechannelListData();
    },
    // 在树节点后面添加数量
    renderContent(h, { node, data, store }) {
      let count = "";
      if (data.probeChannelNum > 0) {
        count = '(' + data.probeChannelNum + ')'
      }
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span style="margin-left: 8px;color: green">{count}</span>
        </span>
      );
    },

    // 修改重复（周几）
    checkboxOptions(value, checkData) {

      let po_obj = {
        id: checkData.id,
        enable: checkData.enable,
        runState: checkData.runState,
        runTime: checkData.runTime,
        runWeek: value.join(","),

      };
      ajax.post({
        url: this.$API.modifyProbeChannelTask + checkData.id,
        data: po_obj,
        success: (response) => {
          this.$message({
            message: response.message,
            type: "success",
          });
        },
        error: (res) => {
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 修改时间
    timeValue(value) {
      console.log(value);
      let date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      let d = date.getDate();
      let timeStr = y + "-" + m + "-" + d + " " + value + ":" + "00";
      let fdate = new Date(timeStr);
      return fdate;
    },
    timeChange(rowData) {
      this.editTime = rowData.runTime;
    },
    // 修改操作
    operationChange(rowData, e) {
      // console.log(rowData, e)
      if (e && e.type == "blur" && this.editTime == rowData.runTime) {
        return;
      }
      let po_obj = {
        id: rowData.id,
        runTime: rowData.runTime,
        runWeek: rowData.runWeekstr.join(","),
        enable: rowData.enable,
        runState: rowData.runState,
      };


      ajax.post({
        url: this.$API.modifyProbeChannelTask + rowData.id,
        data: po_obj,
        success: (response) => {
          this.getProbeChannelTask();
          this.$message({
            message: '修改成功',
            type: "success",
          });
          this.editTime = null;
        },
        error: (res) => {
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    handleDeleteOperation(data) {
      deleteConfirm(this).then((res) => {
        if (res) {
          ajax.post({
            url: this.$API.deleteProbeChannelTask + data.id,
            success: (response) => {
              if (response.success) {
                this.getProbeChannelTask();
                this.$message({
                  type: "success",
                  message: response.message,
                });
              }
            },
            error: (res) => {
              this.$message({
                message: res.message,
                type: "error",
              });
            },
          });
        }
      });
    },
    changeJobByOrgan() {

      if (this.changeJobByOrganId) {
        this.$confirm('确定所有策略都启用?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data={}
          data.id=this.organId
          data.probeChannelTask=this.changeJobByOrganId
          ajax.post({
            url: this.$API.upDataOrgan  + this.organId,
            data:data,
            success: (response) => {
              this.organOptions[this.OrganIdindex].probeChannelTask =this.changeJobByOrganId
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
            },
            error: (res) => {
              this.$message({
                message: res.message,
                type: "error",
              });
            },
          });

        }).catch(() => {
          this.changeJobByOrganId = 0
        });
      }
      else {
        this.$confirm('确定所有策略都停用?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data={}
          data.id=this.organId
          data.probeChannelTask=this.changeJobByOrganId
          ajax.post({
            url: this.$API.upDataOrgan +this.organId,
            data:data,
            success: (response) => {
              this.organOptions[this.OrganIdindex].probeChannelTask =this.changeJobByOrganId
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
            },
            error: (res) => {
              this.$message({
                message: res.message,
                type: "error",
              });
            },
          });


        }).catch(() => {
          this.changeJobByOrganId = 1
        });
      }
    },
  },
  // 网点下的控制策略

};
function getParentIdList(data2, nodeId2) {
  let arrRes = [];
  if (data2.length == 0) {
    if (nodeId2) {
      arrRes.unshift({ id: data2.id, columnName: data2.name });
    }
    return arrRes;
  }
  let rev = (data, nodeId) => {
    for (let i = 0, length = data.length; i < length; i++) {
      let node = data[i];
      if (node.id == nodeId) {
        arrRes.unshift({ id: node.id, columnName: node.name });
        rev(data2, node.parentId);
        break;
      } else {
        if (node.children) {
          rev(node.children, nodeId);
        }
      }
    }
    return arrRes;
  };
  arrRes = rev(data2, nodeId2);
  return arrRes;
}
</script>

<style lang="stylus" scoped>
.ruleequipment-tab-title-row {
  height: 0.5rem;
  background-color: #0d2c5a;
  border-bottom: solid 0.01rem #0d235a;
  -webkit-box-shadow: inset 0px 5px 20px 0px rgba(80, 160, 191, 0.5);
  box-shadow: inset 0px 5px 20px 0px rgba(80, 160, 191, 0.5);
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  margin-bottom: 0.1rem;

  div {
    width: 2rem;
    height: 0.44rem;
    line-height: 0.44rem;
    margin-left: 0.08rem !important;
    border-radius: 5px 5px 0px 0px;
    border: solid 1px #0d235a !important;
    border-bottom: 0 !important;
    margin-top: 0.06rem !important;
    color: #fff !important;
    font-size: 0.16rem !important;
    padding: 0 20px;
    display: inline-block;
    box-sizing: border-box;
    cursor: pointer;
  }

  .ruleequipmenttype_on {
    background-color: #16214d !important;
    color: #fff !important;
  }
}

>>> {
  .control-Action-page {
    position: absolute;
    top: 0.5rem;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 0.2rem;
    overflow: auto;

      .head-section {
        .table-head {
          /* margin-top 0.2rem */
          height: 0.43rem;
          line-height: 0.43rem;
          font-size: 0.16rem;
          font-weight: normal;
          float: left;
        }

        header {
          float: right;
        }
      
    }

    .table-section {
      position: absolute;
      top: 0.72rem;
      left: 0.2rem;
      right: 0.2rem;
      bottom: 0.2rem;
   
    }

    .content {
      .content-head {
        text-align: right;
      }

      .area-table-section {
        position: absolute;
        top: 0.66rem;
        left: 0.2rem;
        right: 0.2rem;
        bottom: 0.2rem;
      }
    }
  }

  .dialog-left {
    .table-head {
      height: 0.3rem;
      margin-top: 0.2rem;
      font-size: 0.16rem;
      font-weight: normal;
    }

    .table-section {
      position: absolute;
      top: 1.2rem;
      left: 0.2rem;
      right: 0.2rem;
      bottom: 0.2rem;
    }

    .dia-table-section {
      height: 300px;
    }
  }

  .el-table__body tr {
    cursor: pointer;
  }

  .el-table--striped .el-table__body tr.el-table__row--striped.current-row td, .el-table__body tr.current-row > td {
    color: #fff;
    background-color: rgba(68, 199, 244, 0.2) !important;
  }

  .el-table__body-wrapper {
    overflow-y: auto !important;
  }

  .el-table .el-checkbox__label {
    color: #fff;
  }

  .el-button.is-round {
    padding: 3px 6px;
  }

  .temperature-txt {
    padding: 0 0.1rem;
    font-size: 0.16rem;
    color: #fff;
  }

  .el-select--mini {
    width: 60px;

    .el-input--suffix .el-input__inner {
      padding-right: 20px;
      padding-left: 10px;
    }
  }

  .air-table-item {
    margin-right: 0.1rem;
  }

  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner, .el-radio__input.is-disabled.is-checked .el-radio__inner {
    background: #409EFF;
  }

  .el-button {
    padding: 0.12rem 0.16rem;
  }

  .el-dialog__footer {
    padding-top: 0;
    padding-bottom: 0.3rem;
  }

  .el-form-item:last-child {
    margin-bottom: 0 !important;
  }

  .area-add {
    width: 380px;
    margin: 0 auto;

    .el-select {
      width: 300px;
    }
  }
}

.equipment-title {
  display: flex;
  margin-bottom: 10px;
}

>>>.equipment-title .el-checkbox__label {
  color: #fff;
}

>>>.equipment-title .el-checkbox {
  min-width: 81px;
  margin-right: 10px;
}

.working-hours-container {
  position: absolute;
  top: 0.5rem;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 0.2rem;
  overflow: auto;
  background-color: $pageBg;
}

.e-t-r-equipment-row {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  width: 7rem;
  padding: 0.2rem;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  background: #16214d;
  overflow: auto;
}
.e-t-r-equipment-row {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  width: 7rem;
  padding: 0.2rem;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  background: #16214d;
  overflow: auto;
}

.e-t-r-rule-row {
  position: absolute;
  left: 7rem;
  right: 0;
  top: 0;
  bottom: 0;
  padding: 0.19rem 0.2rem;
  overflow: auto;
  background: #202c5f;
}

>>>.el-table--striped .el-table__body tr.el-table__row--striped.current-row td, >>>.el-table__body tr.current-row > td {
  color: #fff;
  background-color: rgba(68, 199, 244, 0.2) !important;
}

.e-t-r-rule-box {
  display: flex;
}

.left, .right {
  width: 360px;
  height: 8.1rem;
  padding: 10px;
  border: 1px solid #fff;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.dialog-Action-btn {
  width: 200px;
  padding: 0.2rem;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.dialog-Action-btn .el-button {
  display: block;
  margin: 0.2rem auto;
}
.dialogrule_worktype .el-radio {
    margin-bottom: 10px;
}
>>>.el-dialog .prodtransfer input {
    color: #000;
}
>>>.el-switch__label {
    color:#fff}
>>>.el-switch__label.is-active {
    color: #fff;
}
.el-table .el-checkbox__label, .el-table .el-radio__label, .el-checkbox {
    color: #fff;
  }
>>>.el-radio__label {
    color: #fff;
}
>>>.el-table--striped .el-table__body tr.el-table__row--striped td
    background-color #2a3c6d
</style>
